<template>
	<Wrapper>
		<input_native
			@input="$emit('input', $event)"
			placeholder="输入手机验证码"
			maxlength="6"
			type="number"/>
		<view class="code code_access" v-if="retryTime === leaveTime" @tap="getValideCode">获取验证码</view>
		<view class="code code_retry" v-else-if="leaveTime < retryTime && leaveTime > 0">({{leaveTime}})后重新发送</view>
		<view class="code code_access" v-else @tap="getValideCode">重新发送</view>
	</Wrapper>
</template>

<script>
	import Wrapper from '../wrapper/index.vue'
	import input_native from '../index.vue'
	let retryTime = 60 // 秒
	let interval = null
	export default {
		components: {
			Wrapper, input_native
		},
		props: {
			phone: {
				type: String,
				default: ''
			},
		},
		data() {
			return {
				retryTime: retryTime,
				leaveTime: retryTime
			}
		},
		onUnload() {
			clearInterval(interval)
		},
		methods: {
			getValideCode(e) {
				if(!this.phone) {
					uni.showToast({
						title: '请先输入手机号码！',
						icon: 'none'
					})
					return
				}
				if(!/^[1][3,4,5,7,8][0-9]{9}$/.test(this.phone)) {
					uni.showToast({
						title: '请输入正确的手机号码！',
						icon: 'none'
					})
					return
				}
				this.http.POST({
					name: 'smscode',
					params: {
						mobilePhone: this.phone
					}
				}).then(res => {
					if (res.result === 'success') { // 请求成功
						this.leaveTime = retryTime - 1
						interval = setInterval(() => {
							if(this.leaveTime > 0) {
								this.leaveTime = this.leaveTime - 1
							} else {
								clearInterval(interval)
							}
						}, 1000)
					} else { // 请求失败允许再次获取
						this.leaveTime = -1
					}
				}).catch(res => {
					this.leaveTime = -1
				})
			}
		}
	}
</script>

<style>
	.code {
		position: absolute;
		right: 0upx;
		top: 0upx;
		bottom: 0upx;
		width: 219upx;
		font-size: 28upx;
		display: flex;
		align-items: center;
		justify-content: center;
		border-left: 1upx solid #DDDDDD;
		z-index: 2;
	}
	.code_access {
		color: var(--theme-color);
	}
	.code_retry {
		color: #BBBBBB;
	}
</style>
